package org.linlinjava.litemall.core.express;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.express.WxMaExpressDelivery;
import cn.binarywang.wx.miniapp.bean.express.WxMaExpressPath;
import cn.binarywang.wx.miniapp.bean.express.request.*;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.exception.BadRequestException;
import org.linlinjava.litemall.core.express.dao.ExpressInfo;
import org.linlinjava.litemall.core.express.dao.Traces;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrderGoods;
import org.linlinjava.litemall.db.domain.LitemallWxExpress;
import org.linlinjava.litemall.db.root.AddressBase;
import org.linlinjava.litemall.db.root.DetailBase;
import org.linlinjava.litemall.db.service.LitemallSystemConfigService;
import org.linlinjava.litemall.db.service.LitemallWxExpressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class WxExpressService {
    private final Log logger = LogFactory.getLog(WxExpressService.class);

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private LitemallSystemConfigService systemConfigService;

    @Autowired
    private LitemallWxExpressService litemallWxExpressService;

    /**
     *测试订单轨迹
     */
    public void testTrace(String orderId, String waybillId) {
        Map<String, String> expressConfig = systemConfigService.listExpress();
        LitemallWxExpress litemallWxExpress = litemallWxExpressService.queryByDeliveryId(expressConfig.get("litemall_express_delivery_id"));
        testUpdateWxOrder(orderId, expressConfig.get("litemall_express_delivery_id"), litemallWxExpress.getBizId(), waybillId);
    }


    /**
     * 设置系统默认物流服务
     */
    public void setService(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder) {
        Map<String, String> expressConfig = systemConfigService.listExpress();
        LitemallWxExpress litemallWxExpress = litemallWxExpressService.queryByDeliveryId(expressConfig.get("litemall_express_delivery_id"));
        builder.deliveryId(expressConfig.get("litemall_express_delivery_id"));
        builder.bizId(litemallWxExpress.getBizId());
        WxMaExpressDelivery.ServiceType service = new WxMaExpressDelivery.ServiceType();
        service.setServiceType(Integer.valueOf(expressConfig.get("litemall_express_service_type")));
        service.setServiceName(expressConfig.get("litemall_express_service_type_name"));
        builder.service(service);
    }

    /**
     * 设置包裹信息和分享信息
     * @param builder
     * @param details
     */
    public void setInfo(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder, List<? extends DetailBase> details, String path) {
        WxMaExpressOrderCargo cargo = new WxMaExpressOrderCargo();
        cargo.setCount(1);
        cargo.setWeight(1);
        cargo.setSpaceHeight(1);
        cargo.setSpaceLength(1);
        cargo.setSpaceWidth(1);
        ArrayList<WxMaExpressOrderCargoDetail> detailList = new ArrayList<>();
        for (DetailBase goods : details) {
            WxMaExpressOrderCargoDetail cargoDetail = new WxMaExpressOrderCargoDetail();
            cargoDetail.setCount(goods.getNumber().intValue());
            cargoDetail.setName(goods.getName());
            detailList.add(cargoDetail);
        }
        cargo.setDetailList(detailList);
        builder.cargo(cargo);
        // 商品信息
        WxMaExpressOrderShop shop = new WxMaExpressOrderShop();
        DetailBase firstGoods = details.get(0);
        shop.setGoodsName(firstGoods.getName());
        shop.setGoodsCount(details.size());
        shop.setWxaPath(path);
        shop.setImgUrl(firstGoods.getPicUrl());
        builder.shop(shop);
    }

    /**
     * 设置发件人
     * @param builder
     */
    public void setSender(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder, AddressBase addressBase) {
        WxMaExpressOrderPerson sender = new WxMaExpressOrderPerson();
        sender.setName(addressBase.getConsignee());
        sender.setMobile(addressBase.getMobile());
        String address = addressBase.getAddress();
        List<String> addresses = new ArrayList<>(Arrays.asList(address.split(" ")));
        if (addresses.size() < 4) {
            throw new BadRequestException("地址信息错误");
        }
        sender.setProvince(addresses.get(0));
        sender.setCity(addresses.get(1));
        sender.setArea(addresses.get(2));
        for (int i = 0; i < 3; i++) {
            addresses.remove(0);
        }
        String detailAddress = String.join(" ", addresses);
        sender.setAddress(detailAddress);
        builder.sender(sender);
    }

    /**
     * 设置收件人
     * @param builder
     */
    public void setReceiver(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder, AddressBase addressBase) {
        WxMaExpressOrderPerson receiver = new WxMaExpressOrderPerson();
        receiver.setName(addressBase.getConsignee());
        receiver.setMobile(addressBase.getMobile());
        String address = addressBase.getAddress();
        List<String> addresses = new ArrayList<>(Arrays.asList(address.split(" ")));
        if (addresses.size() < 4) {
            throw new BadRequestException("地址信息错误");
        }
        receiver.setProvince(addresses.get(0));
        receiver.setCity(addresses.get(1));
        receiver.setArea(addresses.get(2));
        for (int i = 0; i < 3; i++) {
            addresses.remove(0);
        }
        String detailAddress = String.join(" ", addresses);
        receiver.setAddress(detailAddress);
        builder.receiver(receiver);
    }

    /**
     * 将系统管理员设为发件人
     * @param builder
     */
    public void setSystemSender(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder) {
        WxMaExpressOrderPerson sender = new WxMaExpressOrderPerson();
        Map<String, String> senderConfig = systemConfigService.listSender();
        sender.setName(senderConfig.get("litemall_sender_name"));
        sender.setMobile(senderConfig.get("litemall_sender_mobile"));
        sender.setProvince(senderConfig.get("litemall_sender_province"));
        sender.setCity(senderConfig.get("litemall_sender_city"));
        sender.setArea(senderConfig.get("litemall_sender_area"));
        sender.setAddress(senderConfig.get("litemall_sender_address"));
        builder.sender(sender);
    }

    /**
     * 将系统管理员设为收件人
     * @param builder
     */
    public void setSystemReceiver(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder) {
        Map<String, String> senderConfig = systemConfigService.listSender();
        builder.openid(senderConfig.get("litemall_sender_openid"));
        WxMaExpressOrderPerson receiver = new WxMaExpressOrderPerson();
        receiver.setName(senderConfig.get("litemall_sender_name"));
        receiver.setMobile(senderConfig.get("litemall_sender_mobile"));
        receiver.setProvince(senderConfig.get("litemall_sender_province"));
        receiver.setCity(senderConfig.get("litemall_sender_city"));
        receiver.setArea(senderConfig.get("litemall_sender_area"));
        receiver.setAddress(senderConfig.get("litemall_sender_address"));
        builder.receiver(receiver);
    }

    /**
     * 设置默认报价信息
     * @param builder
     */
    public void setDefaultInsured(WxMaExpressAddOrderRequest.WxMaExpressAddOrderRequestBuilder builder) {
        WxMaExpressOrderInsured.WxMaExpressOrderInsuredBuilder insuredBuilder = WxMaExpressOrderInsured.builder();
        insuredBuilder.insuredValue(0);
        WxMaExpressOrderInsured insured = insuredBuilder.build();
        builder.insured(insured);
    }

    /**
     * 获取物流轨迹
     * @param waybillId
     * @param deliveryId
     * @param openid
     * @param orderId
     * @return
     * @throws WxErrorException
     */
    public WxMaExpressPath getPath(String waybillId, String deliveryId, String openid, String orderId) throws WxErrorException {
        WxMaExpressGetOrderRequest.WxMaExpressGetOrderRequestBuilder builder = WxMaExpressGetOrderRequest.builder();
        builder.waybillId(waybillId);
        builder.deliveryId(deliveryId);
        builder.openid(openid);
        builder.orderId(orderId);
        WxMaExpressPath path = wxMaService.getExpressService().getPath(builder.build());
        return path;
    }

    @Async
    public void testUpdateWxOrder(String orderId, String deliveryId, String bizId, String waybillId) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        WxMaExpressTestUpdateOrderRequest.WxMaExpressTestUpdateOrderRequestBuilder builder2 = WxMaExpressTestUpdateOrderRequest.builder();
        builder2.bizId(bizId);
        builder2.orderId(orderId);
        builder2.deliveryId(deliveryId);
        builder2.waybillId(waybillId);
        builder2.actionTime(System.currentTimeMillis() / 1000);
        builder2.actionType(100001);
        builder2.actionMsg("您的货物揽件成功");
        try {
            wxMaService.getExpressService().testUpdateOrder(builder2.build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        builder2 = WxMaExpressTestUpdateOrderRequest.builder();
        builder2.bizId(bizId);
        builder2.orderId(orderId);
        builder2.deliveryId(deliveryId);
        builder2.waybillId(waybillId);
        builder2.actionTime(System.currentTimeMillis() / 1000);
        builder2.actionType(100003);
        builder2.actionMsg("您的货物已交给业务员: 肾");
        try {
            wxMaService.getExpressService().testUpdateOrder(builder2.build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        builder2 = WxMaExpressTestUpdateOrderRequest.builder();
        builder2.bizId(bizId);
        builder2.orderId(orderId);
        builder2.deliveryId(deliveryId);
        builder2.waybillId(waybillId);
        builder2.actionTime(System.currentTimeMillis() / 1000);
        builder2.actionType(200001);
        builder2.actionMsg("您的货物已到三十里铺");
        try {
            wxMaService.getExpressService().testUpdateOrder(builder2.build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        builder2 = WxMaExpressTestUpdateOrderRequest.builder();
        builder2.bizId(bizId);
        builder2.orderId(orderId);
        builder2.deliveryId(deliveryId);
        builder2.waybillId(waybillId);
        builder2.actionTime(System.currentTimeMillis() / 1000);
        builder2.actionType(300002);
        builder2.actionMsg("您的货物开始派送：派送员 刘大脑袋");
        try {
            wxMaService.getExpressService().testUpdateOrder(builder2.build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        builder2 = WxMaExpressTestUpdateOrderRequest.builder();
        builder2.bizId(bizId);
        builder2.orderId(orderId);
        builder2.deliveryId(deliveryId);
        builder2.waybillId(waybillId);
        builder2.actionTime(System.currentTimeMillis() / 1000);
        builder2.actionType(300003);
        builder2.actionMsg("您的货物已签收");
        try {
            wxMaService.getExpressService().testUpdateOrder(builder2.build());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
}
